package cn.chendd.redis.utils;

import cn.chendd.redis.constants.RedisConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.atomic.AtomicLong;

/**
 * RedisUtils工具类
 *
 * @author chendd
 * @date 2023/5/19 22:00
 */
public final class RedisUtils {

    private RedisUtils() {

    }

    @SuppressWarnings("unchecked")
    public static <T> RedisTemplate<String , T> getWriteRedisTemplate() {
        return SpringBeanFactory.getBean(RedisConstants.WRITE_REDIS_TEMPLATE , RedisTemplate.class);
    }

    public static StringRedisTemplate getWriteStringRedisTemplate() {
        return SpringBeanFactory.getBean(RedisConstants.WRITE_STRING_REDIS_TEMPLATE , StringRedisTemplate.class);
    }

    private static final AtomicLong READ_STRING_REDIS_TEMPLATE = new AtomicLong(0);

    private static final AtomicLong READ_REDIS_TEMPLATE = new AtomicLong(0);

    @SuppressWarnings("unchecked")
    public static <T> RedisTemplate<String, T> getReadRedisTemplate() {
        long value = READ_REDIS_TEMPLATE.addAndGet(1L);
        if (value % 2 == 0) {
            return SpringBeanFactory.getBean(RedisConstants.READ1_REDIS_TEMPLATE , RedisTemplate.class);
        } else {
            return SpringBeanFactory.getBean(RedisConstants.READ2_REDIS_TEMPLATE , RedisTemplate.class);
        }
    }

    public static StringRedisTemplate getReadStringRedisTemplate() {
        long value = READ_STRING_REDIS_TEMPLATE.addAndGet(1L);
        if (value % 2 == 0) {
            return SpringBeanFactory.getBean(RedisConstants.READ1_STRING_REDIS_TEMPLATE , StringRedisTemplate.class);
        } else {
            return SpringBeanFactory.getBean(RedisConstants.READ2_STRING_REDIS_TEMPLATE , StringRedisTemplate.class);
        }
    }

}
